'''
同步城市天气编码
'''
from django.core.management.base import BaseCommand, CommandError
from weather.models import CityNumber


class Command(BaseCommand):
    '''
    实现自定义命令 sync_city
    '''
    can_import_settings = True
    help = 'Implement custom naming: "sync_city".'

    def handle(self, *args, **options):
        with open('assets/cityCode.txt', 'r') as f:
            all_lines = [line for line in f.read().splitlines() if line.strip()]
            # print("==>> all_lines", len(all_lines))
        try:
            CityNumber.objects.all().delete()
            print("==>> CityNumber is empty!")
        except Exception as e:
            self.stdout.write(self.style.ERROR('Empty CityNumber error!'))
            return

        city_instances = []
        for line in all_lines:
            city_name, city_number = line.split(" ")
            city_instances.append(CityNumber(city_number=city_number, city_name=city_name))
        # print("==>>> city_instances", len(city_instances))
        try:
            CityNumber.objects.bulk_create(city_instances)
        except Exception as e:
            self.stdout.write(self.style.ERROR('CityNumber bulk_create error!'))
            return

        self.stdout.write(self.style.SUCCESS('Successfully write all datas in %s!') % CityNumber.__name__)